package cn.guet.spider.ctrip.task.parser;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.guet.base.spider.DirectoryUtil;
import cn.guet.base.spider.IParser;
import cn.guet.base.spider.http.HttpClientUtil;
import cn.guet.spider.ctrip.entity.Hotel;

/**
 * 携程酒店解析器
 *
 * @author SAGITTAR
 */
@Component(value = "hotelParser")
public class HotelParser implements IParser<Elements, List<Hotel>> {

    private static final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool();

    @Value(value = "${destination.path.base}")
    private String baseUrl;

    @Override
    public List<Hotel> parse(Elements source) {
        String path = DirectoryUtil.getCorrectDirectory(baseUrl, "hotel");
        return source.stream().map(element -> {
            Hotel hotel = new Hotel();
            String imageUrl = HttpClientUtil.validUrl(element.select("img").attr("src"));
            hotel.setImageUrl(imageUrl);
            String name = element.select("a[data-dopost]").first().ownText();
            EXECUTOR_SERVICE.submit(() -> HttpClientUtil.downloadFile(imageUrl, path, name, false));
            hotel.setName(name);
            // 所属区域
            String zone = element.select("p.hotel_item_htladdress").first().text();
            String address = StringUtils.replaceAll(zone, " *", StringUtils.EMPTY);
            hotel.setBusinessArea(address.substring(0, address.lastIndexOf("。") + 1));
            return hotel;
        }).collect(Collectors.toList());
    }

    @Override
    public void release() {
        EXECUTOR_SERVICE.shutdown();
    }
}
